package com.sankuai.inf.leaf.server.service;

//import com.alibaba.druid.pool.DruidDataSource;

import com.sankuai.inf.leaf.segment.dao.LeafAllocDao;
import com.sankuai.inf.leaf.segment.dao.impl.LeafAllocDaoImpl;
import com.sankuai.inf.leaf.segment.model.LeafAllocEntity;
import com.sankuai.inf.leaf.server.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

//import com.sankuai.inf.leaf.common.PropertyFactory;
//import com.sankuai.inf.leaf.server.Constants;
//import java.util.Properties;

/**
 * @author final
 * @description
 * @date 2019-09-11 15:38
 */
@Slf4j
@Service
public class LeafAllocService {
    LeafAllocDao leafAllocDao;

//    DruidDataSource dataSource;
    @Autowired
DataSource dataSource;

    public LeafAllocService() throws SQLException {
//        Properties properties = PropertyFactory.getProperties();
//        // Config dataSource
//        dataSource = new DruidDataSource();
//        dataSource.setUrl(properties.getProperty(Constants.LEAF_JDBC_URL));
//        dataSource.setUsername(properties.getProperty(Constants.LEAF_JDBC_USERNAME));
//        dataSource.setPassword(properties.getProperty(Constants.LEAF_JDBC_PASSWORD));
//        dataSource.init();
//        // Config Dao
//        leafAllocDao = new LeafAllocDaoImpl(dataSource);
    }

    @PostConstruct
    private void init(){
        leafAllocDao = new LeafAllocDaoImpl(dataSource);
    }

    public List<LeafAllocEntity> listLeafAllocEntity() {
        return leafAllocDao.listLeafAllocEntity();
    }

    public void updateLeafAllocEntity(LeafAllocEntity leafAllocEntity) throws CommonException {
        LeafAllocEntity leafAllocEntityByBizTag = leafAllocDao.getLeafAllocEntityByBizTag(leafAllocEntity.getBizTag());
        if (ObjectUtils.isEmpty(leafAllocEntityByBizTag)) {
            throw new CommonException(100508, "此业务不存在");
        }
        try {
            leafAllocDao.updateLeafAllocEntity(leafAllocEntity);
        } catch (Exception e) {
            log.error("updateLeafAllocEntity error:{}", e);
            throw new CommonException(100508, "修改失败");
        }
    }

    public void insertLeafAllocEntity(LeafAllocEntity leafAllocEntity) throws CommonException {
        LeafAllocEntity leafAllocEntityByBizTag = leafAllocDao.getLeafAllocEntityByBizTag(leafAllocEntity.getBizTag());
        if (!ObjectUtils.isEmpty(leafAllocEntityByBizTag)) {
            throw new CommonException(100510, "此业务已存在");
        }
        try {
            leafAllocDao.insertLeafAllocEntity(leafAllocEntity);
        } catch (Exception e) {
            log.error("insertLeafAllocEntity error:{}", e);
            throw new CommonException(100511, "新增失败");
        }
    }
}
